// pages/shopcar/shopcar.js
var app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    isempty:false,
    num:0,//商品数量
    total:0,
    isEdit: false,
    selectAll: false,
    imgPath:app.globalData.imgPath,//
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;
    wx.request({
      url: app.globalData.reqPath + 'shop/MembersCart',
      header: { authorization: app.globalData.authorization },
      success: function ({ data, header }) {
        if (header.authorization && header.authorization != app.globalData.authorization) {
          app.globalData.authorization = header.authorization;
        }
        if (data.code == 200) {
          let list = data.data;
          if(list.length==0){
            self.setData({isempty:true})
          }
          // let num=0;
          // for(let i in list){
          //   num+=list[i].quantity;
          // }
          // list=list.map(function(item){
          //     item.selected=false;
          //     return item;
          // })
          
          self.setData({ list:list,num:list.length})
          self.getTotalPrice()
        }
      }
    })
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //点击选中
  selectList(e) {
    let index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    let carts = this.data.list;                    // 获取购物车列表
    let checked = carts[index].checked;         // 获取当前商品的选中状态
    if (checked == 0) {
      checked = 1;
    } else {
      checked = 0;
    }
    carts[index].checked=checked;              // 改变状态
    // wx.request({
    //   url: '',
    // })

    let selectedcarts = carts.filter(function (item) {
      return item.checked
    })
    if (selectedcarts.length == carts.length) {
      this.setData({ selectAll: true })
    } else {
      this.setData({ selectAll: false })
    }
    this.setData({
      list: carts
    });
    this.getTotalPrice();                           // 重新获取总价
  },
  //增加数量 
  addCount(e) {
    let index = e.currentTarget.dataset.index;
    let self = this;
    let carts = this.data.list;
    let num = carts[index].quantity;
    let result = [];
    if (num < carts[index].stock) {
      num = num + 1;
      wx.request({
        url: app.globalData.reqPath + 'shop/MembersCart/' + carts[index].id,
        data: {
          quantity: num,
          id: carts[index].id,
          skuId: carts[index].skuId,
          checked: carts[index].checked,
          createAt: carts[index].createAt,
          productId: carts[index].productId,
          productName: carts[index].productName,
          salePrice: carts[index].salePrice,
          skuImg: carts[index].skuImg,
          skuName: carts[index].skuName,
          stock: carts[index].stock,
          userId: carts[index].userId,
          weight: carts[index].weight
        },
        method: "PUT",
        header: { authorization: app.globalData.authorization },
        success: function ({ data, header }) {
          if (header.authorization && header.authorization != app.globalData.authorization) {
            app.globalData.authorization = header.authorization;
          }
          if (data.code == 200) {
            console.log(data)
            // self.onLoad();
          }

        }
      })
    } else {
      wx.showModal({
        title: "商品库存不足",
        content: "试试其他商品吧",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            //console.log('用户点击确定')
          }
        }
      })
    }

    carts[index].quantity = num;
    this.setData({
      list: carts
    });

    this.getTotalPrice();
  },
  // 减少数量
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let self = this;
    let carts = this.data.list;
    let num = carts[index].quantity;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].quantity = num;
    wx.request({
      url: app.globalData.reqPath + 'shop/MembersCart/' + carts[index].id,
      data: {
        quantity: num,
        id: carts[index].id,
        skuId: carts[index].skuId,
        checked: carts[index].checked,
        createAt: carts[index].createAt,
        productId: carts[index].productId,
        productName: carts[index].productName,
        salePrice: carts[index].salePrice,
        skuImg: carts[index].skuImg,
        skuName: carts[index].skuName,
        stock: carts[index].stock,
        userId: carts[index].userId,
        weight: carts[index].weight
      },
      method: "PUT",
      header: { authorization: app.globalData.authorization },
      success: function ({ data, header }) {
        if (header.authorization && header.authorization != app.globalData.authorization) {
          app.globalData.authorization = header.authorization;
        }
        if (data.code == 200) {
          console.log(data)
          // self.onLoad();
        }

      }
    })

    this.setData({
      list: carts
    });
    this.getTotalPrice();
  },
  //计算总价
  getTotalPrice: function () {
    let list = this.data.list;
    let total = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i].checked) {                   // 判断选中才会计算价格
        total += list[i].quantity * list[i].vipPrice;     // 所有价格加起来
      }
    }
    this.setData({                               
      list: list,
      total: total.toFixed(2)
    })
  },
  //全选
  selectAll(e) {
    let selectAll = this.data.selectAll;    // 是否全选状态
    selectAll = !selectAll;
    let carts = this.data.list;
    for (let i = 0; i < carts.length; i++) {
      carts[i].checked = selectAll;            // 改变所有商品状态
    }
    this.setData({
      selectAll: selectAll,
      list: carts
    });
    this.getTotalPrice();                               // 重新获取总价
  },
  suborder: function () {//结算 // shop / orders
    let carts = this.data.list;
    let sublist = [];
    sublist = carts.filter(function (item) {
      return item.checked;
    })
    if (sublist.length == 0) {
      wx.showToast({
        title: '请勾选结算商品',
        icon: 'none'
      })
      return false;
    }
    wx.setStorage({
      key: 'sublist',//缓存存提交订单的信息
      data: sublist,
    })
    wx.navigateTo({
      url: '/pages/carSuborder/carSuborder?r=1',
    })
    this.deleteList();
  },
  toedit:function(){//编辑
    this.setData({ isEdit:true})
  },
  deleteList:function(){//删除
    let self = this;
    let carts = this.data.list;
    let delList = [];
    for (let i = 0; i < carts.length; i++) {
      if (carts[i].checked) {
        delList.push(carts[i].id)
      }
    }
    carts = carts.filter(function (item, index) {
      return !item.checked
    })
    console.log(delList)
    this.setData({
      goodList: carts
    });
    wx.request({
      url: app.globalData.reqPath + 'shop/MembersCart/deletes',
      method: "POST",
      header: { authorization: app.globalData.authorization },
      data: {
        ids: delList,
      },
      success: function ({ data, header }) {
        if (header.authorization && header.authorization != app.globalData.authorization) {
          app.globalData.authorization = header.authorization;
        }
        console.log(data)
        if (data.code == 200) {
          // wx.showToast({
          //   title: '删除成功',
          //   icon: 'none',
          //   success: function () {
              self.onLoad();
          //  }
         // })

        }
      }
    })
    //console.log(carts)
    if (!carts.length) {                  // 如果购物车为空
      this.setData({
        isempty: true            
      });
    } else {                              // 如果不为空
      this.getTotalPrice();           // 重新计算总价格
    }
  },
  doneedit:function(){//删除完成
    this.setData({ isEdit: false})

  }
})